<template>
  <div class="main user-layout-register">
    <h3><span>注册</span></h3>
    <a-form ref="formRegister" :form="form" id="formRegister">
      <a-form-item
          label="用户名"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol">
        <a-input
            size="large"
            placeholder="请输入用户名"
            v-decorator="['loginName', {rules: [
                  { required: true, message: '请输入用户名', trigger: 'blur' },
                  { type: 'string', min: 2, message: '用户名不允许小于2位', trigger: 'blur' }]}]"/>
      </a-form-item>

      <a-form-item
          label="昵称"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol">
        <a-input
            size="large"
            placeholder="请输入昵称"
            v-decorator="['userName']"/>
      </a-form-item>

      <a-popover
          placement="rightTop"
          :trigger="['focus']"
          :getPopupContainer="(trigger) => trigger.parentElement"
          v-model="state.passwordLevelChecked">
        <template slot="content">
          <div :style="{ width: '240px' }">
            <div :class="['user-register', passwordLevelClass]">强度：<span>{{ passwordLevelName }}</span></div>
            <a-progress :percent="state.percent" :showInfo="false" :strokeColor=" passwordLevelColor "/>
            <div style="margin-top: 10px;">
              <span>请至少输入 6 个字符。建议不要使用容易被猜到的密码。</span>
            </div>
          </div>
        </template>
        <a-form-item
            label="密码"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol">
          <a-input-password
              size="large"
              @click="handlePasswordInputClick"
              placeholder="至少6位密码，区分大小写"
              v-decorator="['loginPwd', {rules: [
                { required: true, message: '至少6位密码，区分大小写'},
                { validator: this.validatePwd }],
                validateTrigger: ['change', 'blur']}]"
          ></a-input-password>
        </a-form-item>
      </a-popover>

      <a-form-item
          label="确认密码"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol">
        <a-input-password
            size="large"
            placeholder="确认密码"
            v-decorator="['loginPwd2', {rules: [
              { required: true, message: '至少6位密码，区分大小写' },
              { validator: this.validatePwd2 }],
              validateTrigger: ['change', 'blur']}]"
        ></a-input-password>
      </a-form-item>

      <a-form-item
          label="手机号"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol">
        <a-input
            size="large"
            placeholder="11 位手机号"
            v-decorator="['userPhone', {rules: [
                { validator: this.validatePhone, trigger: 'blur' } ]}]">
        </a-input>
      </a-form-item>

      <a-form-item
          label="身份证号"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol">
        <a-input
            size="large"
            placeholder="身份证号"
            v-decorator="['idCard', {rules: [
                { validator: this.validateCard, trigger: 'blur' } ]}]">
        </a-input>
      </a-form-item>

      <a-form-item>
        <a-button
            size="large"
            type="primary"
            htmlType="submit"
            class="register-button"
            :loading="confirmLoading"
            @click.stop.prevent="handleSubmit"
            :disabled="confirmLoading">注册
        </a-button>
        <router-link class="login" :to="{ name: 'login' }">使用已有账户登录</router-link>
      </a-form-item>

    </a-form>
  </div>
</template>

<script>
import {getSmsCaptcha} from '@/api/login'
import {deviceMixin} from '@/store/device-mixin'
import {addUser, validateLoginName} from "@/api/basic/user";
import md5 from "md5";

const levelNames = {
  0: '低',
  1: '低',
  2: '中',
  3: '强'
}
const levelClass = {
  0: 'error',
  1: 'error',
  2: 'warning',
  3: 'success'
}
const levelColor = {
  0: '#ff0000',
  1: '#ff0000',
  2: '#ff7e05',
  3: '#52c41a'
}
export default {
  name: 'Register',
  components: {},
  mixins: [deviceMixin],
  data () {
    return {
      form: this.$form.createForm(this),
      labelCol: {
        xs: {span: 24},
        sm: {span: 5}
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 18}
      },

      state: {
        time: 60,
        smsSendBtn: false,
        passwordLevel: 0,
        passwordLevelChecked: false,
        percent: 10,
        progressColor: '#FF0000'
      },
      confirmLoading: false
    }
  },
  computed: {
    passwordLevelClass () {
      return levelClass[this.state.passwordLevel]
    },
    passwordLevelName () {
      return levelNames[this.state.passwordLevel]
    },
    passwordLevelColor () {
      return levelColor[this.state.passwordLevel]
    }
  },
  methods: {
    validatePwd (rule, value, callback) {
      if (value === undefined || value === null || value.length < 6) {
        callback(new Error("长度不足6位！"))
      }
      let level = 0

      // 判断这个字符串中有没有数字
      if (/[0-9]/.test(value)) {
        level++
      }
      // 判断字符串中有没有字母
      if (/[a-zA-Z]/.test(value)) {
        level++
      }
      // 判断字符串中有没有特殊符号
      if (/[^0-9a-zA-Z_]/.test(value)) {
        level++
      }
      this.state.passwordLevel = level
      this.state.percent = level * 30
      if (level >= 2) {
        if (level >= 3) {
          this.state.percent = 100
        }
        callback()
      } else {
        if (level === 0) {
          this.state.percent = 10
        }
        callback()
      }
    },

    validatePwd2 (rule, value, callback) {
      const password = this.form.getFieldValue('loginPwd')
      if (value === undefined) {
        callback(new Error('请输入密码'))
      }
      if (value && password && value.trim() !== password.trim()) {
        callback(new Error('两次密码不一致'))
      }
      callback()
    },
    // 前端验证手机号码
    validatePhone (rule, value, callback) {
      const reg = /^[1][3-9][0-9]{9}$/
      if (value === '' || value === undefined || value === null) {
        callback()
      } else {
        if ((!reg.test(value)) && value !== '') {
          callback(new Error('请输入正确的电话号码'))
        } else {
          callback()
        }
      }
    },
    // 前端验证身份证号
    validateCard (rule, value, callback) {
      const reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
      if (value === '' || value === undefined || value === null) {
        callback()
      } else {
        if (!reg.test(value)) {
          callback(new Error('请输入正确的身份证号码'))
        } else {
          callback()
        }
      }
    },

    handlePasswordInputClick () {
      if (!this.isMobile) {
        this.state.passwordLevelChecked = true
        return
      }
      this.state.passwordLevelChecked = false
    },

    handleSubmit () {
      const {form: {validateFields}, state, $router} = this
      this.confirmLoading = true
      validateFields((errors, values) => {
        if (!errors) {
          validateLoginName({'loginName': values.loginName})
              .then(() => {
                values.loginPwd = md5(values.loginPwd)
                delete values.loginPwd2
                addUser(values).then(() => {
                  this.visible = false
                  this.confirmLoading = false
                  this.form.resetFields()
                  state.passwordLevelChecked = false
                  $router.push({name: 'registerResult', params: {...values}})
                }).catch(err => {
                  this.confirmLoading = false
                  this.$message.error(err.result || '添加失败！')
                })
              }).catch(err => {
            this.confirmLoading = false
            this.$message.error(err.result || '用户名已经存在！')
          })
        } else {
          this.confirmLoading = false
        }
      })
    },

    requestFailed (err) {
      this.$notification['error']({
        message: '错误',
        description: ((err.response || {}).data || {}).message || '请求出现错误，请稍后再试',
        duration: 4
      })
      this.confirmLoading = false
    }
  },
  watch: {
    'state.passwordLevel' (val) {
      // console.log(val)
    }
  }
}
</script>
<style lang="less">
.user-register {

  &.error {
    color: #ff0000;
  }

  &.warning {
    color: #ff7e05;
  }

  &.success {
    color: #52c41a;
  }

}

.user-layout-register {
  .ant-input-group-addon:first-child {
    background-color: #fff;
  }
}
</style>
<style lang="less" scoped>
.user-layout-register {

  & > h3 {
    font-size: 16px;
    margin-bottom: 20px;
  }

  .getCaptcha {
    display: block;
    width: 100%;
    height: 40px;
  }

  .register-button {
    width: 50%;
  }

  .login {
    float: right;
    line-height: 40px;
  }
}
</style>
